package com.yt.order.api.cms;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.order.models.vo.RepairOrderVO;
import com.yt.user.models.dto.MaintainerInfoDTO;
import com.yt.user.models.service.IMaintainerInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
import com.yt.order.models.service.IRepairOrderService;
import com.yt.order.models.bo.RepairOrderSaveBO;
import com.yt.order.models.bo.RepairOrderBO;
import com.yt.order.models.dto.RepairOrderDTO;

/**
 * 维修订单详情控制器
 *
 * @author thekai
 * @Date 2025-10-30 09:30:13
 */

@RestController
@RequestMapping("/cms/repairOrder")
@Slf4j
@Api(value = "RepairOrderController",tags = "维修订单详情接口")
public class RepairOrderController {

    @DubboReference
    private IRepairOrderService repairOrderService;
    @DubboReference
    private IMaintainerInfoService maintainerInfoService;


    @ApiOperation(value = "添加维修订单详情", notes = "添加维修订单详情")
    @PostMapping(value = "/insert")
    public Result insert(RepairOrderSaveBO saveBO) {
        boolean flag = repairOrderService.add(saveBO);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存维修订单详情", notes = "保存维修订单详情")
    public Result save(RepairOrderSaveBO saveBO) {
        if (saveBO.getId() == null) {
            //添加
            return insert(saveBO);
        } else {
            return update(saveBO);
        }
    }

    @ApiOperation(value = "修改维修订单详情", notes = "修改维修订单详情")
    @PostMapping("/update")
    public Result update(RepairOrderSaveBO saveBO) {
        RepairOrderDTO dto = new RepairOrderDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setId(saveBO.getId());
        boolean flag = repairOrderService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @PostMapping("/updateStatus")
    @ApiOperation(value = "修改状态", notes = "修改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
            , @ApiImplicitParam(name = "status", value = "订单状态（0 待派单 / 1 维修中 / 2 已完成 / 3 已取消）", required = true, paramType = "query", dataType = "Integer")
    })
    public Result updateStatus(Long id, Integer status) {
        RepairOrderDTO dto = new RepairOrderDTO();
        dto.setId(id);
        dto.setStatus(status);
        boolean flag = repairOrderService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @ApiOperation(value = "删除维修订单详情", notes = "删除维修订单详情")
    @ApiImplicitParam(name = "id", value = "维修订单详情id", required = true, paramType = "query", dataType = "Long")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Long id) {
        boolean flag = repairOrderService.deleteById(id);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @PostMapping("/deleteBatch")
    @ApiOperation(value = "批量删除维修订单详情", notes = "批量删除维修订单详情")
    @ApiImplicitParam(name = "ids", value = "ids:以逗号隔开", required = true, paramType = "query", dataType = "String")
    public Result deleteBatch(@RequestParam("ids") String ids) {
        if (StrUtils.isEmpty(ids)) {
            return new Result(CodeEnum.FAIL_100002);
        }
        String[] arr = ids.split(",");
        repairOrderService.deleteBatchIds(Arrays.asList(arr));
        return new Result<>();
    }

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找", notes = "根据id查找")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    public Result<RepairOrderDTO> get(@RequestParam("id") Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        RepairOrderDTO dto = repairOrderService.selectById(id);

        return new Result<>(dto);
    }


    @ApiOperation(value = "添加维修订单详情", notes = "添加维修订单详情")
    @PostMapping(value = "/addOrder")
    public Result addOrder(@RequestBody RepairOrderSaveBO saveBO) {
        boolean flag = repairOrderService.add(saveBO);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }

    @ApiOperation(value = "删除维修订单详情", notes = "删除维修订单详情")
    @ApiImplicitParam(name = "id", value = "维修订单详情id", required = true, paramType = "query", dataType = "Long")
    @PostMapping("/deleteOrder")
    public Result deleteOrder(@RequestParam("id") Long id) {
        boolean flag = repairOrderService.deleteById(id);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @ApiOperation(value = "修改维修订单详情", notes = "修改维修订单详情")
    @PostMapping("/updateOrder")
    public Result updateOrder(@RequestBody RepairOrderSaveBO saveBO) {
        RepairOrderDTO dto = new RepairOrderDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setId(saveBO.getId());
        boolean flag = repairOrderService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @PostMapping("/queryOrder")
    @ApiOperation(value = "查询订单", notes = "查询订单信息")
    public Result<List<RepairOrderVO>> queryOrder() {
        List<RepairOrderVO> repairOrderVOS = repairOrderService.query();
        return new Result<>(repairOrderVOS);
    }

    @ApiOperation(value = "维修订单详情列表", notes = "维修订单详情列表")
    @PostMapping("/queryPageList")
    public Result<Page<RepairOrderDTO>> queryPageList(@RequestBody RepairOrderBO bo) {
        // 验证分页参数
        if (bo.getPageNo() == null || bo.getPageNo() < 1) {
            bo.setPageNo(1);
        }
        if (bo.getPageSize() == null || bo.getPageSize() < 1 || bo.getPageSize() > 100) {
            bo.setPageSize(10);
        }
        Wrapper<RepairOrderDTO> wrapper = new EntityWrapper<>();

        if (bo.getStatus() != null) {
            wrapper.eq("status", bo.getStatus());

        }
        Page<RepairOrderDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = repairOrderService.selectPage(page, wrapper);

        return new Result<>(page);
    }

    @PostMapping("/takeEmployee")
    @ApiOperation(value = "员工接单", notes = "员工接单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "maintainerId", value = "员工id", required = true, paramType = "query", dataType = "Long")
    })
    public Result<Boolean> receiveOrder(@RequestParam("id") Long id, @RequestParam("maintainerId") Long maintainerId) {
        if (id == null || maintainerId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        RepairOrderDTO repairOrderDTO = repairOrderService.selectById(id);
        //不存在报错
        if (repairOrderDTO == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        //存在设置员工id
        repairOrderDTO.setMaintainerId(maintainerId);
        //将状态改变为处理中
        repairOrderDTO.setStatus(1);
        //更新数据库
        boolean flag = repairOrderService.updateById(repairOrderDTO);

        return new Result<>(flag);
    }

    //自动派单
    @PostMapping("/order")
    @ApiOperation(value = "自动派单", notes = "自动派单")
    public Result pandan() {
        Wrapper<RepairOrderDTO> orderWrapper = new EntityWrapper<>();
        orderWrapper.eq("status", 0);
        List<RepairOrderDTO> orderLists = repairOrderService.selectList(orderWrapper);
        if (orderLists == null || orderLists.isEmpty()) {
            return new Result<>(CodeEnum.FAIL_USER_200008);
        }

        // 2. 遍历每个待派单的订单，逐个分配
        for (RepairOrderDTO order : orderLists) {
            Integer orderType = order.getType(); // 订单类型（0水电 / 1家具 / 2网络）

            // 3. 查询对应类型的维修人员（工作中、状态正常、未删除）
            Wrapper<MaintainerInfoDTO> maintainerWrapper = new EntityWrapper<>();
            maintainerWrapper.eq("type", orderType)        // 类型匹配
                    .eq("work_status", 1)         // 工作中
                    .eq("status", 1)             // 状态正常
                    .eq("is_delete", 0);         // 未删除
            List<MaintainerInfoDTO> maintainers = maintainerInfoService.selectList(maintainerWrapper);
            if (maintainers == null || maintainers.isEmpty()) {
                log.warn("无对应类型的维修人员，订单ID：{}，类型：{}", order.getId(), orderType);
                continue; // 或返回错误，根据业务需求决定
            }

            // 4. 统计每个维修人员的“未完成订单量”，找到订单量最少的人
            MaintainerInfoDTO targetMaintainer = null;
            int minOrderCount = Integer.MAX_VALUE; // 初始设为最大整数

            for (MaintainerInfoDTO maintainer : maintainers) {
                // 统计该维修人员的未完成订单数（status≠2）
                Wrapper<RepairOrderDTO> countWrapper = new EntityWrapper<>();
                countWrapper.eq("maintainer_id", maintainer.getId())
                        .ne("status", 2); // 排除已完成订单
                int orderCount = repairOrderService.selectCount(countWrapper);

                // 找到订单量最少的维修人员
                if (orderCount < minOrderCount) {
                    minOrderCount = orderCount;
                    targetMaintainer = maintainer;
                }
            }

            // 5. 分配订单：更新订单的maintainer_id
            if (targetMaintainer != null) {
                order.setMaintainerId(targetMaintainer.getId());
                order.setStatus(1); // 订单状态改为“维修中”
                repairOrderService.updateById(order);
                log.info("订单ID：{} 分配给维修人员ID：{}", order.getId(), targetMaintainer.getId());
            } else {
                log.warn("未找到可分配的维修人员，订单ID：{}", order.getId());
            }
        }

        return new Result<>(CodeEnum.SUCCESS);




    }
}